import {
  Cartesian3,
  ClockRange,
  ClockStep,
  JulianDate,
  Math as CesiumMath,
  ScreenSpaceEventHandler,
  ScreenSpaceEventType,
  Viewer,
} from '@space8/czm-plugin';

// 灌片区域，绕点旋转
function cameraRotatorIrrigate(viewer: Viewer) {
  const options = {
    lng: 118.8938555432328,
    lat: 32.36197471265026,
    height: 10,
    heading: 5.15,
    pitch: -0.6,
    roll: 6.2,
  };
  const position = Cartesian3.fromDegrees(options.lng, options.lat, options.height);
  const pitch = CesiumMath.toRadians(-24);
  const angle = 360 / 60;
  const distance = 6000;
  const startTime = JulianDate.fromDate(new Date());
  viewer.clock.startTime = startTime.clone();
  viewer.clock.currentTime = startTime.clone();
  viewer.clock.clockRange = ClockRange.CLAMPED;
  viewer.clock.clockStep = ClockStep.SYSTEM_CLOCK;
  const initialHeading = viewer.camera.heading;
  const timeExecution = () => {
    const delTime = JulianDate.secondsDifference(viewer.clock.currentTime, viewer.clock.startTime);
    const heading = CesiumMath.toRadians(delTime * angle) + initialHeading;
    viewer.scene.camera.setView({
      destination: position,
      orientation: {
        heading: heading,
        pitch: pitch,
      },
    });
    viewer.scene.camera.moveBackward(distance);
  };
  viewer.clock.onTick.addEventListener(timeExecution);

  // 点击取消绕点旋转
  const handler = new ScreenSpaceEventHandler(viewer.canvas);
  handler.setInputAction(() => {
    viewer.clock.onTick.removeEventListener(timeExecution);
  }, ScreenSpaceEventType.LEFT_CLICK);
}

export default cameraRotatorIrrigate;
